<template xmlns="http://www.w3.org/1999/html">
  <el-card class="page-container">
    <!-- 头部导航 -->
    <template #header>
      <div class="header">
        <el-page-header @back="goBack" :content="'房源详情'"/>
      </div>
    </template>

    <!-- 基本信息区块 -->
    <div class="section" v-loading="loading">
      <el-descriptions title="基本信息" :column="2" border v-if="!isEditing">
        <el-descriptions-item label="房源标题">{{ itemData.title || '暂无标题' }}</el-descriptions-item>
        <el-descriptions-item label="房源类型">
          <el-tag :type="detailData.type === '0' ? 'warning' : 'success'">
            {{ detailData.type === '0' ? '出售' : '出租' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="价格">
          <span class="price">¥{{ detailData.price?.toLocaleString() }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="面积">{{ detailData.area }}㎡</el-descriptions-item>
        <el-descriptions-item label="地址">{{ detailData.address }}</el-descriptions-item>
        <el-descriptions-item label="小区">{{ detailData.communityName }}</el-descriptions-item>
        <el-descriptions-item label="居室类型">{{ detailData.descriptionName }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="statusColor[detailData.status]">
            {{ statusMap[detailData.status] }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ formatDate(detailData.publishTime) }}</el-descriptions-item>
        <el-descriptions-item label="详情">{{ itemData.remake || '暂无详细描述' }}</el-descriptions-item>
        <el-descriptions-item label="经纪人姓名">{{ detailData.intermediaryName || '暂无详细描述' }}</el-descriptions-item>
        <el-descriptions-item label="经纪人电话">{{ itemData.intermediaryTel || '暂无详细描述' }}</el-descriptions-item>
      </el-descriptions>

      <el-form :model="detailData" label-width="120px" v-else>
        <el-form-item label="房源标题">
          <el-input v-model="detailData.title"></el-input>
        </el-form-item>
        <el-form-item label="房源类型">
          <el-radio-group v-model="detailData.type">
            <el-radio label="0">出售</el-radio>
            <el-radio label="1">出租</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="detailData.price"></el-input>
        </el-form-item>
        <el-form-item label="面积">
          <el-input v-model="detailData.area"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="detailData.address"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="detailData.status">
            <el-option v-for="(value, key) in statusMap" :key="key" :label="value" :value="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详情">
          <el-input v-model="detailData.remake"></el-input>
        </el-form-item>
        <el-form-item label="中介名称">
          <el-select
              v-model="detailData.intermediaryId"
              placeholder="经纪人姓名"
              clearable
              filterable
          >
            <el-option
                v-for="item in IntListOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="小区名称">
          <el-select
              v-model="detailData.communityId"
              placeholder="请选择小区"
              clearable
              filterable
          >
            <el-option
                v-for="item in ComListOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="居室描述" prop="description">
          <el-select
              v-model="detailData.description"
              placeholder="请输入居室描述"
              clearable
              filterable
          >
            <el-option
                v-for="item in housewearOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="经纪人电话">
          <el-input v-model="itemData.intermediaryTel"></el-input>
        </el-form-item>
      </el-form>
    </div>

    <!-- 图片画廊 -->
    <div class="section" v-loading="loading">
      <h3 class="section-title">房源图片</h3>
      <!--      点击预览-->
      <el-row :gutter="20" v-if="!isEditing">
        <!-- 封面大图 -->
        <el-col :span="24" class="mb-20">
          <div class="image-frame cover-frame">
            <el-image
                :src="detailData.cover || defaultImage "
                :preview-src-list="previewList"
                fit="cover"
                class="frame-image preview-image"
                @error="handleImageError"
                v-if="!isEditing">
              <template #error>
                <div class="image-error">封面加载失败</div>
              </template>
            </el-image>
            <el-upload
                v-else
                action="your_upload_api_url"
                :show-file-list="false"
                :on-success="(res) => handleUploadSuccess(res, 'cover')"
                :before-upload="beforeUpload"
            >
              <el-button type="primary">上传封面图片</el-button>
            </el-upload>
          </div>
        </el-col>
        <!-- 六个相框 -->
        <el-col
            v-for="(img, index) in imageList"
            :key="index"
            :span="8"
            class="mb-20">
          <div class="image-frame preview-image">
            <el-image
                :src="img || defaultImage"
                :preview-src-list="previewList"
                fit="cover"
                class="frame-image"
                @error="handleImageError"
                v-if="!isEditing">
              <template #error>
                <div class="image-error">图片加载失败</div>
              </template>
            </el-image>
            <el-upload
                v-else
                action="your_upload_api_url"
                :show-file-list="false"
                :on-success="(res) => handleUploadSuccess(res, index)"
                :before-upload="beforeUpload"
            >
              <el-button type="primary">上传图片</el-button>
            </el-upload>
          </div>
        </el-col>
      </el-row>

      <!--      点击上传-->
      <el-form :model="detailData" label-width="100px" v-if="isEditing">
        <el-form-item>
          <el-upload
              class="avatar-uploader"
              :auto-upload="true"
              :show-file-list="false"
              action="/api/upload"
              name="file"
              :headers="{'Authorization': tokenStore.token}"
              :on-success="handleUploadSuccess">
            <img v-if="detailData.cover" :src="detailData.cover" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>

          <el-upload
              class="avatar-uploader"
              :auto-upload="true"
              :show-file-list="false"
              action="/api/upload"
              name="file"
              :headers="{'Authorization': tokenStore.token}"
              :on-success="handleUploadSuccessprc1">
            <img v-if="itemData.housesPic" :src="itemData.housesPic" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>

          <el-upload
              class="avatar-uploader"
              :auto-upload="true"
              :show-file-list="false"
              action="/api/upload"
              name="file"
              :headers="{'Authorization': tokenStore.token}"
              :on-success="handleUploadSuccessprc2">
            <img v-if="itemData.housesPic2" :src="itemData.housesPic2" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>

          <el-upload
              class="avatar-uploader"
              :auto-upload="true"
              :show-file-list="false"
              action="/api/upload"
              name="file"
              :headers="{'Authorization': tokenStore.token}"
              :on-success="handleUploadSuccessprc3">
            <img v-if="itemData.housesPic3" :src="itemData.housesPic3" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>

          <el-upload
              class="avatar-uploader"
              :auto-upload="true"
              :show-file-list="false"
              action="/api/upload"
              name="file"
              :headers="{'Authorization': tokenStore.token}"
              :on-success="handleUploadSuccessprc4">
            <img v-if="itemData.housesPic4" :src="itemData.housesPic4" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>

          <el-upload
              class="avatar-uploader"
              :auto-upload="true"
              :show-file-list="false"
              action="/api/upload"
              name="file"
              :headers="{'Authorization': tokenStore.token}"
              :on-success="handleUploadSuccessprc5">
            <img v-if="itemData.housesPic5" :src="itemData.housesPic5" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>

          <el-upload
              class="avatar-uploader"
              :auto-upload="true"
              :show-file-list="false"
              action="/api/upload"
              name="file"
              :headers="{'Authorization': tokenStore.token}"
              :on-success="handleUploadSuccessprc6">
            <img v-if="itemData.housesPic6" :src="itemData.housesPic6" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

    </div>

    <!-- 评论信息 -->
    <div class="section" v-loading="loading" v-if="!isEditing">
      <el-input
          v-model="MessageModel.content"
          style="width: 240px"
          size="large"
          placeholder="输入评论"
      />
      <el-button type="primary" @click="addMessage">发布评论</el-button>
      <!-- 内容 -->
      <el-table :data="messageListData" style="width: 100%" v-loading="loading">
        <el-table-column label="头像" prop="userPic" width="120">
          <template #default="{ row }">
            <el-image
                :style="{ width: '50px', height: '50px', borderRadius: '50%' }"
                :src="row.userPic"
                v-if="row.userPic"
                fit="cover"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <span v-else>无封面</span>
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="nickname" width="100px" />
        <el-table-column label="评论时间" prop="createTime" width="120px" />
        <el-table-column label="评论" prop="content" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <!--            <el-button-->
            <!--                :icon="Document"-->
            <!--                circle-->
            <!--                plain-->
            <!--                type="success"-->
            <!--                @click="huifuMessage(row)"-->
            <!--            />-->
            <el-button
                :icon="Edit"
                circle
                plain
                type="primary"
                @click="editMessage(row)"
                v-if="userinfoId === row.userId"
            />
            <el-button
                :icon="Delete"
                circle
                plain
                type="danger"
                @click="deleteMessage(row)"
                v-if="userinfoId === row.userId"
            />
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无评论" />
        </template>

      </el-table>
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="titleView" width="40%">
      <el-form :model="MessageModel" label-width="100px" style="padding-right: 30px">
        <el-form-item label="评论内容">
          <el-input v-model="MessageModel.content" minlength="1" maxlength="15"></el-input>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <!-- 取消按钮 -->
          <el-button @click="dialogVisible = false">取消</el-button>
          <!-- 确认按钮 -->
          <el-button type="primary" @click="titleView === '发布评论'? addMessage() : updataMessageDite()"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button v-if="!isEditing" @click="startEditing">修改详情</el-button>
      <el-button v-if="isEditing" type="primary" @click="submitEdit">提交</el-button>
      <el-button v-if="isEditing" @click="cancelEdit">取消</el-button>
      <el-button @click="goBack">返回列表</el-button>
    </div>
  </el-card>
</template>

<script setup>
import defaultImage from '@/assets/imgmoren.png'

import {ref, computed, onMounted} from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {addMessageService, deleteMessageService, getMessageList, updateMessage} from "@/api/message.js"
import {getHouseItem, getHouse, updateHouse} from '@/api/housesList.js'
import {useTokenStore} from "@/stores/token.js";
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Document, Edit, Plus} from "@element-plus/icons-vue";
const tokenStore = useTokenStore();
const router = useRouter()
const route = useRoute()
const houseId = route.params.id
import { useUserInfoStore } from "@/stores/userinfo.js"
import {getHousewearList} from "@/api/housewear.js";
import {getCusList, getIntList, getLanList} from "@/api/user.js";
import {getCommunityList} from "@/api/community.js";
const userInfoStore = useUserInfoStore()

const userinfoId = userInfoStore.info.id;

// 控制编辑状态
const isEditing = ref(false);
// 保存原始数据
const originalDetailData = ref({});
const originalItemData = ref({});
const originalImageList = ref([]);

// 评论列表数据模型
const messageListData = ref([])
// 控制添加/编辑弹窗显示
const dialogVisible = ref(false)
// 获取房源列表数据
const messageList = async () => {
  try {
    const result = await getMessageList({
      // userId: userinfoId,
      houseId: houseId,
    });
    clearData();
    if (result && result.res) {
      messageListData.value = result.res;
    } else {
      console.error('接口返回数据格式不正确，缺少 data 属性');
      ElMessage.error('加载房源列表失败，接口返回数据格式不正确');
    }
  } catch (error) {
    console.error('数据获取失败:', error)
    ElMessage.error('加载房源列表失败')
  }finally {
    loading.value = false; // 结束加载
  }
}

messageList();

// 状态映射配置
const statusMap = {
  '0': '待审核',
  '1': '已发布',
  '2': '已下架',
  '3': '已成交'
}

const statusColor = {
  '0': 'warning',
  '1': 'success',
  '2': 'info',
  '3': ''
}

// 数据响应
const detailData = ref({
  area: '',
  price: '',
  description: '',
  type: '',
  publishTime: '',
  status: '',
  cover: '',
  landlordName: '',
  intermediaryName: '',
  communityName: '',
  customerName: '',
  intermediaryId:'',
  communityId:'',
  descriptionName:'',
})
const itemData = ref({
  title:'',
  housesPic:'',
  housesPic2:'',
  housesPic3:'',
  housesPic4:'',
  housesPic5:'',
  housesPic6:'',
  remake:'',
  intermediaryTel:'',
})
const selecthouseid = ref({
  id: houseId
})
const selecthouseItem = ref({
  housesId: houseId
})
// 获取数据
// 加载状态
const loading = ref(false)
const loadData = async () => {
  try {
    loading.value = true
    const [detailRes, itemRes] = await Promise.all([
      getHouse(selecthouseid.value),
      getHouseItem(selecthouseItem.value)
    ])

    if (detailRes?.res) detailData.value = detailRes.res
    if (itemRes?.res) itemData.value = itemRes.res

  } catch (error) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchDropdownOptions()
  loadData()
})


const imageList = computed(() => [
  itemData.value.housesPic,
  itemData.value.housesPic2,
  itemData.value.housesPic3,
  itemData.value.housesPic4,
  itemData.value.housesPic5,
  itemData.value.housesPic6
].filter(url => url))
console.log(imageList)

// 预览图片列表
const previewList = computed(() => [
  detailData.value.cover,
  ...imageList.value.filter(Boolean)
])

// 图片加载失败处理
const handleImageError = (e) => {
  console.error('图片加载失败:', e)
}

// 时间格式化
const formatDate = (dateStr) => {
  if (!dateStr) return '未发布'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`
}

// 交互操作
const handleContact = () => {
  if (!itemData.value.intermediaryTel) {
    ElMessage.warning('暂无中介联系方式')
    return
  }
  ElMessage.success('中介电话'+itemData.value.intermediaryTel)
}

const goBack = () => {
  router.push('/RentingHouses/RentingHouseslist')
}


// 重置表单的正确方式
const MessageModel = ref({
  id:'',
  content: '',
  userId: '',
  houseId: '',
  type:'',
})

// 清空表单数据
const clearData = () => {
  MessageModel.value = {
    content: '',
    userId: '',
    houseId: '',
    type:'',
    id:''
  }
}
// 弹窗标题
const titleView = ref('')
const editMessage = (row) => {
  dialogVisible.value = true;
  titleView.value = '修改评论';
  MessageModel.value = {
    id: row.id,
    content:row.content,
    userId:row.userId,
    houseId:row.houseId,
  }
  console.log('content='+MessageModel.value.content)
}
const updataMessageDite = async () => {
  // 处理空值转换
  const submitData = {
    ...MessageModel.value,
  }
  try {
    let resul = await updateMessage(submitData);
    ElMessage.success('修改成功')
    messageList() // 调用正确的方法刷新评论列表
    dialogVisible.value = false;
    // 重置表单的正确方式
    clearData()
  } catch (error) {
    console.error('修改评论失败:', error)
    ElMessage.error('修改评论失败')
  }
}

// 发布评论
const addMessage = async () => {
  MessageModel.value.userId=userinfoId
  MessageModel.value.houseId=houseId
  MessageModel.value.type="0"
  try {
    await addMessageService(MessageModel.value) // 传递正确的数据
    ElMessage.success('添加成功')
    messageList()
    dialogVisible.value = false
    clearData()
  } catch (error) {
    console.error('发布评论失败:', error)
    ElMessage.error('发布评论失败')
  }
}

// 删除
const deleteMessage = (row) => {
  // 提示用户删除
  ElMessageBox.confirm('是否删除评论?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let resul = await deleteMessageService(row.id);
    messageList();
    ElMessage({
      type:'success',
      message: '删除成功!'
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
}

// 开始编辑
const startEditing = () => {
  isEditing.value = true;
  originalDetailData.value = {...detailData.value};
  originalItemData.value = {...itemData.value};
  originalImageList.value = [...imageList.value];
}

// 提交编辑
const submitEdit = async () => {
  try {
    const submitData = {
      // 优先取detailData的值，若为空则取itemData
      ...Object.fromEntries(
          Object.entries(detailData.value).map(([key, val]) => [
            key,
            val ?? itemData.value[key]
          ])
      ),
      imageList: imageList.value
    };
    await updateHouse(submitData);
    ElMessage.success('提交成功');
    isEditing.value = false;
    loadData();
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
  }
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false;
  detailData.value = {...originalDetailData.value};
  itemData.value = {...originalItemData.value};
  imageList.value = [...originalImageList.value];
}

// 图片上传前校验
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

// 图片上传成功处理
const handleUploadSuccess = (result) => {
  detailData.value.cover = result.res;
}
const handleUploadSuccessprc1 = (result) => {
  itemData.value.housesPic = result.res;
}
const handleUploadSuccessprc2 = (result) => {
  itemData.value.housesPic2 = result.res;
}
const handleUploadSuccessprc3 = (result) => {
  itemData.value.housesPic3 = result.res;
}
const handleUploadSuccessprc4 = (result) => {
  itemData.value.housesPic4 = result.res;
}
const handleUploadSuccessprc5 = (result) => {
  itemData.value.housesPic5 = result.res;
}
const handleUploadSuccessprc6 = (result) => {
  itemData.value.housesPic6 = result.res;
}
// 其他下拉选项数据模型
const IntListOptions = ref([])
const housewearOptions = ref([])
const ComListOptions = ref([])

const fetchDropdownOptions = async () => {
  try {
    const reshouse = await getHousewearList()
    housewearOptions.value = reshouse.res.map(item => ({
      value: item.id,
      label: item.houseType
    }))
    const resCom = await getCommunityList()
    ComListOptions.value = resCom.res.map(item => ({
      value: item.id,
      label: item.name
    }))
    const resint = await getIntList()
    IntListOptions.value = resint.res.map(item => ({
      value: item.id,
      label: item.nickname
    }))
  } catch (error) {
    console.error('获取失败:', error)
    ElMessage.error('加载失败')
  }
}


</script>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .el-tag {
    margin: 2px;
  }
}

.section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.section-title {
  color: #333;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.price {
  color: #f56c6c;
  font-size: 1.2em;
  font-weight: bold;
}

.action-bar {
  text-align: center;
  margin-top: 30px;
  padding: 20px 0;
  border-top: 1px solid #eee;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}


.image-frame {
  /* 移除边框设置 */
  border: none !important; /* 增加强制覆盖 */
  box-shadow: none !important; /* 移除阴影 */
  background: transparent !important; /* 透明背景 */
}

.cover-frame {
  border: none !important;
}

.el-image-viewer__wrapper .el-image-viewer__img {
  border: none !important;
  background: transparent !important;
}
.frame-image {
  width: 100%;
  height: 100%;
  border-radius: 6px;
}
.preview-image {
  width: 450px; /* 设置宽度 */
  height: 300px; /* 设置高度 */
}
.mb-20 {
  margin-bottom: 20px;
}

/* 评论区域样式 */
.avatar-uploader :deep(.el-upload) {
  width: 150px;
  height: 150px;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden; /* 隐藏超出部分 */
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}
.avatar-uploader .avatar {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持比例填充容器 */
}
</style>
